package com.heima.wemedia.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//该拦截器的作用就是用于拦截在网关路由过来的头信息,然后将拦截下来的头信息存入到当前线程中去
public class WmTokenInterceptor implements HandlerInterceptor {
    /**\
     * 前置处理   获取网关存在头信息里面的用户信息 存入线程中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            //存入当当前线程中
            WmThreadLocalUtil.setUser(wmUser);

        }
        return true;
    }

    /**
     *
     * 后置处理 清理Threadlocal中的数据,防止内存溢出
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocalUtil.clear();
    }
}
